import { Controller, All, Req, Res } from '@nestjs/common';
import config from '../config/config';
import { Request, Response } from 'express';
import * as httpProxy from 'http-proxy';

@Controller('')
export class ProxyController {
  @All('')
  daili(@Req() req: Request, @Res() res: Response) {
    // 创建代理对象
    const proxy = httpProxy.createProxyServer({
      // 代理地址为http时
      target: config.target,
      // 是否需要改变原始主机头为目标URL
      changeOrigin: true
      // 重写cookie的作用域
      // cookieDomainRewrite: {
      //   '*': 'dev.yilihuo.com'
      // }

      // 当地址为https时加上秘钥和
      // ssl: {
      //     key: fs.readFileSync('server_decrypt.key', 'utf8'),
      //     cert: fs.readFileSync('server.crt', 'utf8')
      // },
      // if you want to verify the SSL Certs
      // secure: false
    });
    // 配置错误处理
    proxy.on('error', (err, request, response) => {
      response.writeHead(500, {
        'Content-Type': 'text/plain'
      });
      response.status(500).end('服务器异常！');
    });

    proxy.web(req, res);
    return;
  }
}
